using Dapper;
using Finance.Api.Read.Applications.Commands.台账管理;
using Finance.Api.Read.Dtos;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Text;

namespace Finance.Api.Read.Applications.CommandHands.台账管理
{
    public class ProductAlertQueryCommandHandlers : IRequestHandler<ProductAlertQueryCommand, ApiResult<ApiPaging<List<ProductAlertDto>>>>
    {
        private readonly IDapperDb _db;
        private readonly ILogger<ProductAlertQueryCommandHandlers> _logger;

        public ProductAlertQueryCommandHandlers(IDapperDb db, ILogger<ProductAlertQueryCommandHandlers> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<ApiResult<ApiPaging<List<ProductAlertDto>>>> Handle(ProductAlertQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<ApiPaging<List<ProductAlertDto>>>();
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder totalNum = new StringBuilder();

            ApiPaging<List<ProductAlertDto>> res = new ApiPaging<List<ProductAlertDto>>();
            var parameters = new DynamicParameters();
            try
            {
                stringBuilder.Append(@"SELECT 
                            a.Id,
                            a.ProductNo,
                            a.ProductName,
                            a.ProductType,
                            a.ProductNum,
                            a.NumMin,
                            a.NumMax,
                            CASE WHEN a.ProductNum < a.NumMin THEN (a.NumMin - a.ProductNum) ELSE 0 END as ByongNumMin,
                            CASE WHEN a.ProductNum > a.NumMax THEN (a.ProductNum - a.NumMax) ELSE 0 END as ByongNumMax
                    FROM Product a
                    WHERE 1=1
                            AND a.IsDelete=0 ");

                // 货品名称查询条件
                if (!string.IsNullOrEmpty(request.ProductName))
                {
                    stringBuilder.Append(" AND a.ProductName LIKE @ProductName ");
                    parameters.Add("ProductName", $"%{request.ProductName}%");
                }

                // 货品类型查询条件
                if (!string.IsNullOrEmpty(request.ProductType))
                {
                    stringBuilder.Append(" AND a.ProductType = @ProductType ");
                    parameters.Add("ProductType", request.ProductType);
                }

                // 上下限状态查询条件
                if (request.AlertType.HasValue)
                {
                    switch (request.AlertType.Value)
                    {
                        case 1: // 低于下限
                            stringBuilder.Append(" AND a.ProductNum < a.NumMin ");
                            break;
                        case 2: // 高于上限
                            stringBuilder.Append(" AND a.ProductNum > a.NumMax ");
                            break;
                        case 3: // 上下限之间
                            stringBuilder.Append(" AND a.ProductNum >= a.NumMin AND a.ProductNum <= a.NumMax ");
                            break;
                    }
                }

                // 当前库存最小值查询条件
                if (request.ProductNumMin.HasValue)
                {
                    stringBuilder.Append(" AND a.ProductNum >= @ProductNumMin ");
                    parameters.Add("ProductNumMin", request.ProductNumMin.Value);
                }

                // 当前库存最大值查询条件
                if (request.ProductNumMax.HasValue)
                {
                    stringBuilder.Append(" AND a.ProductNum <= @ProductNumMax ");
                    parameters.Add("ProductNumMax", request.ProductNumMax.Value);
                }

                // 构建总数查询SQL
                totalNum.Append(@"SELECT COUNT(1)
                            FROM Product a
                            WHERE 1=1
                                    AND a.IsDelete=0 ");

                // 为总数查询添加相同的查询条件
                if (!string.IsNullOrEmpty(request.ProductName))
                {
                    totalNum.Append(" AND a.ProductName LIKE @ProductName ");
                }

                if (!string.IsNullOrEmpty(request.ProductType))
                {
                    totalNum.Append(" AND a.ProductType = @ProductType ");
                }

                if (request.AlertType.HasValue)
                {
                    switch (request.AlertType.Value)
                    {
                        case 1: // 低于下限
                            totalNum.Append(" AND a.ProductNum < a.NumMin ");
                            break;
                        case 2: // 高于上限
                            totalNum.Append(" AND a.ProductNum > a.NumMax ");
                            break;
                        case 3: // 上下限之间
                            totalNum.Append(" AND a.ProductNum >= a.NumMin AND a.ProductNum <= a.NumMax ");
                            break;
                    }
                }

                if (request.ProductNumMin.HasValue)
                {
                    totalNum.Append(" AND a.ProductNum >= @ProductNumMin ");
                }

                if (request.ProductNumMax.HasValue)
                {
                    totalNum.Append(" AND a.ProductNum <= @ProductNumMax ");
                }

                // 执行总数查询
                int totalCount = await _db.QueryFirst<int>(totalNum.ToString(), parameters);

                // 添加分页和排序
                stringBuilder.Append($" ORDER BY a.Id DESC LIMIT {((request.index - 1) * request.size)}, {request.size}");

                // 执行数据查询
                var list = await _db.Query<ProductAlertDto>(stringBuilder.ToString(), parameters);
                
                // 手动设置序号
                int rowNumber = (request.index - 1) * request.size + 1;
                foreach (var item in list)
                {
                    item.RowNum = rowNumber++;
                }
                
                res.data = list.ToList();
                res.totalcount = totalCount;
                res.totalpcount = (int)Math.Ceiling(totalCount * 1.0 / request.size);
                result.data = res;
                result.message = "库存预警分页查询成功";
                result.Code = Enumcode.ok;
            }
            catch (Exception ex)
            {
                _logger.LogError("库存预警分页查询失败: {Message}", ex.Message);
                result.message = "库存预警分页查询失败";
                result.Code = Enumcode.fail;
                throw;
            }

            return await Task.FromResult(result);
        }
    }
} 